package 简单;

import java.util.Map;

public class 最后一块石头的重量 {

    public static void main(String[] args) {
        int[] stones = {3,7,2};
        System.out.println(lastStoneWeight(stones));

    }

    public static int lastStoneWeight(int[] stones) {
        int length = stones.length;
        if (length ==0){
            return 0;
        }
        if (length ==1){
            return stones[0];
        }
        int[] arr = new int[1001];
        int max = 0;
        int max2;
        for (int stone : stones) {
            arr[stone]++;
            if (stone>max){
                max = stone;
            }
        }
        while (length>1){
            length -= arr[max];
            if (arr[max]%2==0){
                arr[max] = 0;
            }else {
                arr[max] = 0;
                max2 = max-1;
                while (max2>0 && arr[max2]<=0){
                    max2--;
                }
                arr[max2] --;
                arr[max-max2]++;
            }
            while (max>0&&arr[max]<=0) max--;
        }
        return max;
    }
}
